<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><!-- #BeginTemplate "/Templates/maintemplate.dwt" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<!-- #BeginEditable "doctitle" --><title>VectorJep - Vectors and Matrices in JEP</title><!-- #EndEditable --> 
<link rel="stylesheet" type="text/css" href="../main.css" title="style1">
</head>

<body>



<!-- NAVIGATION ---------------------------------------------------- -->
<div id="navcontainer"> 
  <ul>
    <li><a href="../../javadoc/index.html" target="_blank">JavaDoc <img src="../img/new-window-icon.gif" width="15" height="11"></a></li>
  </ul>
  <h1>JEP</h1>
  <ul>
    <li><a href="../index.html">Basic Usage</a></li>
    <li><a href="../variables.html">Variables</a></li>
    <li><a href="../types.html">Data types</a></li>
    <li><a href="../operators.html">Operators</a></li>
    <li><a href="../functions.html">Functions</a></li>
    <li><a href="../advanced.html">Advanced Features</a></li>
    <li><a href="../grammar.html">Grammar</a></li>
    <li><a href="../faq.html">FAQ</a></li>
    <li><a href="../version.html">Version History</a></li>
  </ul>
  <h1>Extensions</h1>
  <ul>
    <li><a href="index.html">Overview</a></li>
    <li><a href="xjep.html">XJep</a></li>
    <li><a href="djep.html">Differentiation</a></li>
    <li><a href="vectorjep.html">Vectors and Matrices</a></li>
    <li><a href="groupjep.html">Groups</a></li>
    <li><a href="version.html">Version History</a></li>
  </ul>
</div>



<div id="centercontent">
<!-- CENTER CONTENT -------------------------------------------------- -->
<!-- #BeginEditable "Text" --> 
        <h1><a name="top"></a>Vectors and Matrices</h1>
<p>
There are two packages which offer support for vectors and matrices
</p><ul>
<li>org.lsmp.djep.vectorJep - standard vector and matrix handling
</li><li>org.lsmp.djep.matrixJep - advanced vector and matrix handling
</li></ul>for most applications the first package should suffice. The
second
package allows differentiation of equations with vectors and matrices;
the overloading of the ^ operator to be both power and cross product;
a speed advantages; and the calculation of the dimensions
of each equation. The downside is that it adds about 65K to the size of
the required packages.

<p>
Most of the functionality is common to both packages and the following
syntax is allow:
</p><ul>
<li><b>Vectors</b>: <tt>[1,2,3]</tt> denotes a vector, variables and equations can be used
	throughout i.e. <tt>[x,y,2*x+3*y]</tt></li>
<li><b>Matrices</b>: <tt>[[1,2],[3,4]]</tt> a matrix with rows [1,2] and [3,4].</li>
<li><b>Tensors</b>: <tt>[[[1,2],[3,4]],[[5,6],[7,8]]]</tt> higher rank tensors are also allowed.</li>
<li><b>Addition and subtraction</b> of vectors, matrices and tensors, using + and -.
</li><li><b>Multiplication</b> of matrices using * (note size of matrices must match).
</li><li><b>Dot product</b> of vectors <tt>[1,2,3].[4,5,6]</tt></li>
<li><b>Cross product</b> of vectors. The ^ operator is overloaded to be either the cross product: <tt>[1,2,3]^[4,5,6]</tt>
	or the power operator 2^3. The ^^ operator can be used to force interpretation as a cross product.</li>
<li>An <tt>ele(vec,index)</tt> function to access the elements of a vector
	and an <tt>ele(matrix,[index1,index2])</tt> to access an element of a matrix.</li><li>As
. is used to represent dot product it cannot normally be used inside a
variable name. This behaviour can be changed by setting a flag in the
parser.<br>
        </li>

</ul>

<p>
Two interactive console applet illustrate the functionality of 
<a href="http://www.singsurf.org/djep/VectorJep.html">VectorJep</a> and
<a href="http://www.singsurf.org/djep/MatrixJep.html">MatrixJep</a>.

  <!-- #BeginLibraryItem "/Library/top bar.lbi" -->
<div class="topbar"><a href="#top"><img src="../img/top.gif" width="38" height="15" name="top"></a></div>
<!-- #EndLibraryItem --><h2><a name="VEC"></a>vectorJep</h2>
<p>
The use of the package can be illustrated by
</p><pre>import org.nfunk.jep.*;
import org.lsmp.djep.vectorJep.*;

public class VectorExample {
    static VectorJep j;
  
    public static void main(String args[])    {
    	// initialise
        j = new VectorJep();
        j.addStandardConstants();
        j.addStandardFunctions();
        j.addComplex();
        j.setAllowUndeclared(true);
        j.setImplicitMul(true);
        j.setAllowAssignment(true);

		// parse and evaluate each equation in turn
		
        doStuff("[1,2,3]");               // Value: [1.0,2.0,3.0]
        doStuff("[1,2,3].[4,5,6]");       // Value: 32.0
        doStuff("[1,2,3]^^[4,5,6]");      // Value: [-3.0,6.0,-3.0]
        doStuff("[1,2,3]+[4,5,6]");       // Value: [5.0,7.0,9.0]
        doStuff("[[1,2],[3,4]]");         // Value: [[1.0,2.0],[3.0,4.0]]
        doStuff("[[1,2],[3,4]]*[1,0]");   // Value: [1.0,3.0]
        doStuff("[1,0]*[[1,2],[3,4]]");   // Value: [1.0,2.0]
        doStuff("[[1,2],[3,4]]*[[1,2],[3,4]]");   // Value: [[7.0,10.0],[15.0,22.0]]
        doStuff("x=[1,2,3]");             // Value: [1.0,2.0,3.0]
        doStuff("x+x");                   // Value: [2.0,4.0,6.0]
        doStuff("x.x");                 // Value: 14.0
        doStuff("x^x");                  // Value: [0.0,0.0,0.0]
        doStuff("ele(x,2)");              // Value: 2.0
        doStuff("y=[[1,2],[3,4]]");       // Value: [[1.0,2.0],[3.0,4.0]]
        doStuff("y * y");                 // Value: [[7.0,10.0],[15.0,22.0]]
        doStuff("ele(y,[1,2])");          // Value: 2.0
		
    }
	// parse, evaluate and print the value of the expression 
    public static void doStuff(String str)    {
        try {
            Node node = j.parse(str);
            Object value = j.evaluate(node);
            System.out.println(str + "\tvalue " + value.toString());
        }
        catch(ParseException e) { System.out.println("Parse error "+e.getMessage()); }
        catch(Exception e) { System.out.println("evaluation error "+e.getMessage()); }
    }
}
</pre>
      <h3>Values returned by evaluate</h3>


  <p> The values returned by <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixJep.html#evaluateRaw(org.nfunk.jep.Node)">evaluateRaw(Node 
    node)</a> or <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixJep.html#getValueAsObject()">getValueAsObject()</a> 
    or <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixJep.html#getVarValue(java.lang.String)">getVarValue(String 
    name)</a> are one of the types in <a href="../../javadoc/org/lsmp/djep/vectorJep/values/package-summary.html"><tt>org.lsmp.djep.vectorJep.values</tt></a>. 
    These are: </p>
  <ul>
<li><a href="../../javadoc/org/lsmp/djep/vectorJep/values/Scaler.html">Scaler</a> Scaler values.</li>
<li><a href="../../javadoc/org/lsmp/djep/vectorJep/values/MVector.html">MVector</a> a vector, note the M to distinguish the class from java.util.Vector.</li>
<li><a href="../../javadoc/org/lsmp/djep/vectorJep/values/Matrix.html">Matrix</a> a matrix.
</li><li><a href="../../javadoc/org/lsmp/djep/vectorJep/values/Tensor.html">Tensor</a> a tensor of rank 3 or higher.
</li><li><a href="../../javadoc/org/lsmp/djep/vectorJep/values/MatrixValueI.html">MatrixValueI</a> an interface defining common methods of above.
</li></ul>
Several methods are common to all types
      <a href="../../javadoc/org/lsmp/djep/vectorJep/values/MatrixValueI.html#getDim()">getDim()</a> (returns the dimension of object)
      <a href="../../javadoc/org/lsmp/djep/vectorJep/values/MatrixValueI.html#getNumEles()">getNumEles()</a> (returns the total number of elements)
      <a href="../../javadoc/org/lsmp/djep/vectorJep/values/MatrixValueI.html#getEle(int)">getEle(i)</a> (returns the i-th element of the object)
      <a href="../../javadoc/org/lsmp/djep/vectorJep/values/MatrixValueI.html#setEle(int, java.lang.Object)">setEle(i,value)</a> (sets the value of an element).
In addition <tt>Matrix</tt> has a <a href="../../javadoc/org/lsmp/djep/vectorJep/values/Matrix.html#getEle(int, int)">getEle(row,col)</a>
and a <a href="../../javadoc/org/lsmp/djep/vectorJep/values/Matrix.html#setEle(int, int, java.lang.Object)">setEle(row,col,value)</a>.
These methods allow the individual elements of vector or matrix to be set and queried.<p></p>

<p>The <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixJep.html#evaluateRaw(org.nfunk.jep.Node)">evaluate(Node node)</a> 
method behaves the same as <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixJep.html#evaluateRaw(org.nfunk.jep.Node)">evaluateRaw(Node node)</a>

however if the result is a Scaler then it will be unwrapped and the
single value will be returned, typically a Double or Complex.</p>



<h3>Printing with vectorJep</h3>
<p>
To keep package size down print facilities are not provided in the
<tt>org.lsmp.djep.vectorJep</tt> package. However it is easy to include
them by using the <tt>org.lsmp.djep.xjep.printVisitor</tt> class.
For example:
</p><pre>import org.lsmp.djep.xjep.PrintVisitor;
....
PrintVisitor pv = new PrintVisitor();
Node node = j.parse("[1,2,3]");
pv.print(node);
String str = pv.toString(node);
</pre>

  <!-- #BeginLibraryItem "/Library/top bar.lbi" -->
<div class="topbar"><a href="#top"><img src="../img/top.gif" width="38" height="15" name="top"></a></div>
<!-- #EndLibraryItem --><h3>Element by element calculations</h3>
<p>
The vectorJep package can be set up so that element by element multiplication and division
is performed instead of matrix multiplication. To switch this mode on
use
</p>
<pre>VectorJep j = new VectorJep();

j.setElementMultiply(true);</pre>
<p>
Once set <tt>[1,2,3]*[4,5,6]</tt> will evaluate to <tt>[4,10,18]</tt>.
</p>

  <!-- #BeginLibraryItem "/Library/top bar.lbi" -->
<div class="topbar"><a href="#top"><img src="../img/top.gif" width="38" height="15" name="top"></a></div>
<!-- #EndLibraryItem --><h3>Functions on Vectors and Matricies</h3>
<p>
Several functions are added with the VectorJep package these are:
</p>
<table border="0" cellspacing="1" cellpadding="2" width="100%" bgcolor="#CCCCCC">
<tr bgcolor="#FFFFFF">
	<th><b>Name</b></th>
	<th><b>Description</b></th>
	<th><b>Examples</b></th>
</tr>
<tr bgcolor="#FFFFFF" valign="top">
	<td>length</td>
	<td>Finds the length of a vector or the number of elements in a matrix or tensor.</td>
	<td><tt>length(5)==1, <tt>length([1,2,3])==3</tt>, <tt>length([[1,2],[3,4]])==4</tt></tt></td>
</tr>
<tr bgcolor="#FFFFFF" valign="top">
	<td>size</td>
	<td>Finds the size of a vector, matrix or tensor.</td>
	<td><tt>size(5)==1</tt>, <tt>size([1,2,3])==3</tt>, <tt>size([[1,2],[3,4],[5,6])==[2,3]</tt></td>
</tr>
<tr bgcolor="#FFFFFF" valign="top">
	<td>det</td>
	<td>The determinant of a square matrix.</td>
	<td><tt>det([[1,2],[3,4]])==-2</tt></td>
</tr>
<tr bgcolor="#FFFFFF" valign="top">
	<td>trace</td>
	<td>The trace of a square matrix.</td>
	<td><tt>trace([[1,2],[3,4]])==5</tt></td>
</tr>
<tr bgcolor="#FFFFFF" valign="top">
	<td>vsum</td>
	<td>The sum of elements in a vector, matrix or tensor.</td>
	<td><tt>vsum([1,2,3])==6</tt>, <tt>vsum([[1,2],[3,4]])==10</tt></td>
</tr>
<tr bgcolor="#FFFFFF" valign="top">
	<td>trans</td>
	<td>The transpose of a matrix.</td>
	<td><tt>trans([[1,2],[3,4]])==[[1,3],[2,4]]</tt></td>
</tr>
<tr bgcolor="#FFFFFF" valign="top">
	<td>getdiag</td>
	<td>Extracts the diagonal from a square matrix.</td>
	<td><tt>getdiag([[1,2],[3,4]])==[1,4]</tt></td>

<tr bgcolor="#FFFFFF" valign="top">
	<td>diag</td>
	<td>Generates a square matrix with a given diagonal.</td>
	<td><tt>diag([1,2,3])==[[1,0,0],[0,2,0],[0,0,3]]</tt></td>
</tr>

<tr bgcolor="#FFFFFF" valign="top">
	<td>GenMat</td>
	<td>Generates vectors and matrixies</td>
	<td>First argument specifies size of the vector (3) and matricies ([2,2]).
	Second argument is formula for each element, constants (1), functions (rand()),
	Third argument (if present) is list of variables used in formula.
	For vectors a single variable is specified whos value runs from 1 to number of elements.
	For matricies a two variable list ([ii,jj]) is specified whos value are the column and row indicies.

<pre>
GenMat(3,1) -> [1,1,1]
GenMat(3,ii,ii) -> [1,2,3]
GenMat(3,rand()) -> [0.343,0.974,0.567]
GenMat([2,2],ii+jj,[ii,jj]) -> [[2,3],[3,4]]
</pre>
</td>
</tr>

<tr bgcolor="#FFFFFF" valign="top">
	<td>ele</td>
	<td>Extracts an element from a vector, matrix or tensor.</td>
	<td><tt>ele([1,2,3],2)==2</tt>, <tt>ele([[1,2],[3,4]],[1,2])==2</tt></td>
</tr>
</table>


<p>
The Map function applies a function to each element of a vector or matrix.
The first argument is the function to apply.
The second argument is either a variable or a list of variables.
The third and subsequent arguments are the vectors or matricies the function is applied to.
During evaluation the variables will be set to each element of the vectors or matricies.
For example
</p>
<pre>Map(x^3,x,[1,2,3]) -> [1.0,8.0,27.0]
Map(x*y,[x,y],[1,2,3],[4,5,6]) -> [4.0,10.0,18.0]
Map(if(x>0,x,0),x,[-2,-1,0,1,2]) -> [0.0,0.0,0.0,1.0,2.0]
Map(abs(x),x,[[-2,-1],[1,2]]) -> [[2.0,1.0],[1.0,2.0]]
</pre>

  <!-- #BeginLibraryItem "/Library/top bar.lbi" -->
<div class="topbar"><a href="#top"><img src="../img/top.gif" width="38" height="15" name="top"></a></div>
<!-- #EndLibraryItem --><h3>variable names with dot in them</h3>
<p>
As the dot <code>.</code> symbol is used for the dot or scaler product, it cannot be normally be
used in a varible name. This behaviour can be switched on or off using
<pre>
jep.getParser().setInitialTokenManagerState(ParserConstants.NO_DOT_IN_IDENTIFIERS);
jep.getParser().setInitialTokenManagerState(ParserConstants.DEFAULT);
</pre>
  <!-- #BeginLibraryItem "/Library/top bar.lbi" -->
<div class="topbar"><a href="#top"><img src="../img/top.gif" width="38" height="15" name="top"></a></div>
<!-- #EndLibraryItem --><h2><a name="MAT"></a>MatrixJep</h2>
<p>
The MatrixJep package offers the same functionality as the VectorJep
package however it is implemented in a different manner internally
which offers a few new features:</p>
      <ul>
        <li>A speed improvement - matrix operations are about a third faster.</li>
        <li>The preprocessing stage is used to calculate the dimension of each node.</li>
        <li>All the features of the XJep package are enabled.</li>
        <li>Differentiation is enabled.</li>
      </ul>
      <p>It is essential that the <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixJep.html#preprocess(org.nfunk.jep.Node)">preprocess</a>
method is called after an equation is parsed. This will find the
dimensions of each node, process the diff operator and set the
equations of variables.

</p>
      <p>A typical example of the use of this package is: (differences from vectorJep are shown in bold)

      </p>
      <pre>import org.nfunk.jep.*;
<b>import org.lsmp.djep.matrixJep.*;</b>
<b>import org.lsmp.djep.matrixJep.nodeTypes.*; // only needed if you wish 
                                          // to find the dimension of a node</b>
public class MatrixExample {
    static MatrixJep j;
    public static void main(String args[])    {
       	// initialise
       	<b>j = new MatrixJep();</b>
       	j.addStandardConstants();
       	j.addStandardFunctions();
       	j.addComplex();
       	j.setAllowUndeclared(true);
       	j.setImplicitMul(true);
       	j.setAllowAssignment(true);
       	
       	// parse and evaluate each equation in turn
       	
       	doStuff("[1,2,3]");               // Value: [1.0,2.0,3.0]
       	doStuff("[1,2,3].[4,5,6]");       // Value: 32.0
       	doStuff("[1,2,3]^^[4,5,6]");      // Value: [-3.0,6.0,-3.0]
       	doStuff("[1,2,3]+[4,5,6]");       // Value: [5.0,7.0,9.0]
       	doStuff("[[1,2],[3,4]]");         // Value: [[1.0,2.0],[3.0,4.0]]
       	doStuff("[[1,2],[3,4]]*[1,0]");   // Value: [1.0,3.0]
       	doStuff("[1,0]*[[1,2],[3,4]]");   // Value: [1.0,2.0]
       	doStuff("[[1,2],[3,4]]*[[1,2],[3,4]]");   // Value: [[7.0,10.0],[15.0,22.0]]
       	doStuff("x=[1,2,3]");             // Value: [1.0,2.0,3.0]
       	doStuff("x+x");                   // Value: [2.0,4.0,6.0]
       	doStuff("x.x");                   // Value: 14.0
       	
       	<b>	// ^ can be used to represent the cross product as well as power.</b>
       	<b>doStuff("x^x");                   // Value: [0.0,0.0,0.0]</b>
       	doStuff("ele(x,2)");              // Value: 2.0
       	doStuff("y=[[1,2],[3,4]]");       // Value: [[1.0,2.0],[3.0,4.0]]
       	doStuff("y * y");                 // Value: [[7.0,10.0],[15.0,22.0]]
       	doStuff("ele(y,[1,2])");          // Value: 2.0
       	<b>// using differentiation
       	doStuff("x=2");	                  // 2.0
       	doStuff("y=[x^3,x^2,x]");         // [8.0,4.0,2.0]
       	doStuff("z=diff(y,x)");	          // [12.0,4.0,1.0]
       	doStuff("diff([x^3,x^2,x],x)");
       	
       	// Finding the dimension of a variable	
       	System.out.println("dim(z) "+((MatrixVariableI) j.getVar("z")).getDimensions());</b>
    }
    // parse, evaluate and print the value of the expression 
    public static void doStuff(String str)    {
        try {
            Node node = j.parse(str);
            <b>Node proc = j.preprocess(node);
            Node simp = j.simplify(proc);</b>
            Object value = j.evaluate(simp);
            <b> // Print the equation and its dimension
            j.print(simp);
            System.out.print("\t dim "+((MatrixNodeI) simp).getDim());</b>
            System.out.println("\tvalue " + value.toString());
        }
        catch(ParseException e) { System.out.println("Parse error "+e.getMessage()); }
        catch(Exception e) { System.out.println("evaluation error "+e.getMessage()); }
    }
}</pre>
    <p>Note that in MatrixJep variables and Node have dimensions. Each variable will be of type 
    <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixVariableI.html">MatrixVariableI</a> 
    and the dimension of this can be found by the 
    <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixVariableI.html#getDimensions()">getDimensions</a> method. 
    After the <a href="../../javadoc/org/lsmp/djep/matrixJep/MatrixJep.html#preprocess(org.nfunk.jep.Node)">preprocess</a>
    method is called the nodes in the parse tree all implement <a href="../../javadoc/org/lsmp/djep/matrixJep/nodeTypes/MatrixNodeI.html">MatrixNodeI</a> 
    which have a <a href="../../javadoc/org/lsmp/djep/matrixJep/nodeTypes/MatrixNodeI.html#getDim()">getDim</a> method. 
    Each node also has a object of type <a href="../../javadoc/org/lsmp/djep/vectorJep/values/MatrixValueI.html">MatrixValueI</a>
    which stores intermediate values. By reusing these objects evaluation speeds are increased by a third.
      </p>

  <!-- #BeginLibraryItem "/Library/top bar.lbi" -->
<div class="topbar"><a href="#top"><img src="../img/top.gif" width="38" height="15" name="top"></a></div>
<!-- #EndLibraryItem --><h2><a name="JAMA"></a>JAMA</h2>

<p>
JAMA <a href="http://math.nist.gov/javanumerics/jama/">http://math.nist.gov/javanumerics/jama/</a>
is a library of matrix fuctions, offering matrix solving, and other advanced
matrix operations.
</p>

<p>
The <a href="../../javadoc/org/lsmp/djep/jama/package-summary.html">org.lsmp.djep.jama</a>
package allows these sophsticated matrix functions to be used with VectorJep and MatrixJep.
Currently only a small subset (solve, rank, inverse) are implemented.


  <!-- #BeginLibraryItem "/Library/top bar.lbi" -->
<div class="topbar"><a href="#top"><img src="../img/top.gif" width="38" height="15" name="top"></a></div>
<!-- #EndLibraryItem --><!-- #EndEditable -->




<!-- FOOTER ---------------------------------------------------------- -->
<div id="footer">
<a href="http://sourceforge.net/tracker/?func=add&group_id=24711&atid=382402">Report bugs / documentation errors</a><br/>
<br/>
&copy; 2006 <a href="http://www.singularsys.com" target="_blank">Singular Systems</a>
</div>
</div> <!-- centercontent -->

</body>
<!-- #EndTemplate --></html>
